# -*- coding:UTF-8 -*-
import datetime
import json
import time
from socket import *

from  multiprocessing import Queue
from threading import Thread


class TcpHelper(object):
    response_list = []
    request_list = []
    
    
    def __init__(self, server_ip, server_port):
        # 创建socket
        self.tcp_client_socket = socket(AF_INET, SOCK_STREAM)
        # 目的信息
        self.server_ip = server_ip
        self.server_port = server_port
        # 链接服务器
        try:
            self.tcp_client_socket.connect((server_ip, server_port))
        except:
            pass
        self.heart_time = self.get_time()
        
        self.response_list = Queue()
        # self.login()
    
    def __send(self, send_data):
        self.heart_time = self.get_time()
        self.tcp_client_socket.send(send_data)
    
    def __listen(self):
        self.recvData = self.tcp_client_socket.recv(1024)
    
    def trans(self, send_data, active):
        send_str = json.dumps(send_data,separators=(',',':'))
        print("send_str:" + send_str)
        str_len = len(send_str)
        length_list = [0, 0, 0, 0, 0]
        if active == "login":
            length_list[0] = 1
        elif active == "msg":
            length_list[0] = 5
        
        import copy
        length_list[1] = str_len // 16777216
        length_list[2] = (str_len % 16777216) // 65536
        length_list[3] = (str_len % 65536) // 256
        length_list[4] = (str_len % 256)
        print("str_len:{}".format(str_len))
        
        header = bytes(length_list)
        
        return header + send_str.encode("utf-8")
    
    def get_time(self):
        return round(time.time() * 1000)
    
    def login(self):
        from init.fileinit import device_key
        login_dict = {}
        login_dict["loginname"] = device_key if device_key!=None else "test"
        login_dict["password"] = "123"
        login_dict["time"] = self.get_time()
        
        send_data = self.trans(login_dict, "login")
        self.__send(send_data)
    
    def heart_core(self):
        print("start heart break")
        self.__send(b"\x63\x00\x00\x00\x00")
    
    def heart(self):
        sub_time = (self.get_time() - self.heart_time)
        if sub_time > 10000:
            self.heart_core()
    
    def message(self, msg):
        print("start send message:{}".format(msg))
        msg_dict = {}
        msg_dict["text"] = msg
        msg_dict["time"] = self.get_time()
        msg_dict['toUserid'] = "main"
        send_data = self.trans(msg_dict, "msg")
        self.__send(send_data)
    
    def close(self):
        # 关闭套接字
        self.tcp_client_socket.close()
    
    def receive(self):
        self.__listen()
        try:
            self.recvData = self.recvData[5:].decode()
        except Exception as e:
            self.recvData = None
    
    def tcp_request_loop(self):
        while True:
            self.receive()
            yield self.recvData
            
    def tcp_new_response(self,response):
        self.response_list.put(response)
    
    def tcp_response_loop(self):
        while True:
            # 当列表为空的时候，返回执行心跳，否则发送消息
            try:
                if self.response_list.empty():
                    self.heart()
                    yield False
                else:
                    self.message(self.response_list.get())
                    yield True
            except:
                self.heart()
                yield False

    

if __name__ == '__main__':
    tcp_hlpr = TcpHelper("127.0.0.1", 5678)
    i = 0
    tcp_hlpr.login()
    
    for value in tcp_hlpr.tcp_response_loop():
        i += 1
        if 0 == i % 10:
            tcp_hlpr.response_list.put("123")
        time.sleep(0.5)
    
    
    
    # for request in tcp_hlpr.tcp_request_loop():
    #     print(request)
